package com.devshephard.rpcframework.rpc.controller;

import com.devshephard.rpcframework.rpc.factory.channel.SingletonClientChannelFactory;
import com.devshephard.rpcframework.rpc.factory.channel.SingletonServerChannelFactory;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@Slf4j
public class NettyRunner{

    private static String RequestRpcProtocol; //是否开启本地服务端

    private static String enableRpcServer; //是否开启本地服务端

    private static String enableRpcClient; //是否开启本地客户端

    private static String currentServerAddress;  //本地Netty地址

    private static String currentServerPort;  //本地Netty端口

    private static String requestServerAddress;  //远程访问服务端地址

    private static String requestServerPort;  //远程访问服务端端口


    public void run() {

        if(!Objects.isNull(RequestRpcProtocol) && "tcp".equals(RequestRpcProtocol.toLowerCase())){ //是否开启RPC类型调用

            new Thread(()->{
                if(enableRpcServer != null && "enable".equals(enableRpcServer)){
                    log.info("Enable Rpc Server");
                    SingletonServerChannelFactory singletonServerChannelFactory = new SingletonServerChannelFactory(); //启动服务端
                    singletonServerChannelFactory.startServerChannel(currentServerAddress,currentServerPort);
                }
            },"Netty-Server").start();

            new Thread(()->{
                if(enableRpcClient != null && "enable".equals(enableRpcClient)){
                    log.info("Enable Rpc Client");
                    SingletonClientChannelFactory singletonClientChannelFactory = new SingletonClientChannelFactory(); //启动客户端
                    singletonClientChannelFactory.startClientChannel(requestServerAddress,requestServerPort);
                }
            },"Netty-Client").start();
        }

    }


    public void setEnvironment(Environment environment) {

        this.RequestRpcProtocol = environment.getProperty("rpc.protocol"); //是否开启本地服务端

        this.enableRpcServer = environment.getProperty("rpc.server"); //是否开启本地服务端

        this.enableRpcClient = environment.getProperty("rpc.client"); //是否开启本地客户端

        this.currentServerAddress = environment.getProperty("rpc.local.address");  //本地Netty地址

        this.currentServerPort = environment.getProperty("rpc.local.port");  //本地Netty端口

        this.requestServerAddress = environment.getProperty("rpc.request.address");    //远程访问服务端地址

        this.requestServerPort = environment.getProperty("rpc.request.port");  //远程访问服务端端口

    }

}
